package com.xinghen.common.core.support.impl;

import com.google.common.collect.Lists;
import com.xinghen.common.base.model.dto.BaseTree;
import com.xinghen.common.core.support.ITree;
import org.apache.commons.collections.CollectionUtils;

import java.io.Serializable;
import java.util.List;
import java.util.Objects;

/**
 * @author xinghen
 * @ClassName: AbstractTreeService
 * @Package: com.xinghen.common.core.support.impl
 * @Description abstract tree service
 * @create 2018-04-17 11:42
 */
public abstract class AbstractTreeService<T extends BaseTree<T, ID>, ID extends Serializable> implements ITree<T, ID> {

    @Override
    public List<T> getChildrenTree(List<T> list, ID pid) {
        List<T> result = Lists.newArrayList();
        for (T t : list) {
            if (Objects.equals(pid, t.getPid())) {
                recursionFn(list, t);
                result.add(t);
            }
        }
        return result;
    }

    @Override
    public List<T> getChildrenList(List<T> list, T t) {
        List<T> result = Lists.newArrayList();
        for (T tree : list) {
            if (Objects.equals(tree.getPid(), t.getId())) {
                result.add(tree);
            }
        }
        return result;
    }

    @Override
    public void recursionFn(List<T> list, T t) {
        if (hasChild(list, t)) {
            List<T> children = getChildrenList(list, t);
            t.setHasChild(true);
            t.setChildren(children);
            for (T child : children) {
                recursionFn(list, child);
            }
        }
    }

    @Override
    public boolean hasChild(List<T> list, T t) {
        return CollectionUtils.isNotEmpty(getChildrenList(list, t));
    }
}
